<template>
  <div class="comment-container">
    <h4>发表评论{{newsid}}</h4>

    <textarea placeholder="请输入要BB的内容(最多吐槽120个字)" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click.native="postMsg">发表评论</mt-button>
    <!-- 评论列表区域 -->
    <div class="comment-group">
      <div class="comment-item" v-for="(item, index) in comments" :key="index">
        <div
          class="comment-item-title"
        >第{{index +1}}楼&nbsp;用户: {{item.user_name}} &nbsp;发表时间: {{item.add_time | dateFromat}}</div>
        <div class="comment-item-body">{{item.content}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click.native="getLoadMore">加载更多</mt-button>
  </div>
</template>

<script>
export default {
  created() {
    // 获取 评论数据
    this.__getComments();
  },
  props: ["newsid"],
  data() {
    return {
      page: 1,
      comments: [],
      msg: '' // 评论的内容
    };
  },
  methods: {
    // ================= 发送网络请求 =================
    async __getComments() {
      const { data: res } = await this.$http.get(
        `getcomments/${this.newsid}?pageindex=${this.page}`
      );
      if (res.status !== 0) return;
      this.comments = this.comments.concat(res.message);
    },
    //==========  事件监听 =============
    getLoadMore() {
      this.page++;
      this.__getComments();
    },
    async postMsg() {
      if(this.msg.trim().length ===0) return this.$Toast('评论内容不能为空')
      const {data: res} = await this.$http.post(`postcomment/${this.newsid}`, {
        content: this.msg.trim()
      })
      if(res.status===0) {
        this.$Toast('评论成功')

        this.comments.unshift({
          user_name: '匿名用户',
          add_time: new Date(),
          content: this.msg.trim()
        })
      }
    }
  }
};
</script>

<style lang='scss' scoped>
.comment-container {
  h4 {
    border-bottom: 1px solid #ccc;
    padding: 10px 0;
  }
  textarea {
    font-size: 13px;
    margin-bottom: 0;
  }

  .comment-item {
    padding-bottom: 5px;
  }
  .comment-item-title {
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    background-color: #ddd;
    margin: 5px 0;
  }
  .comment-item-body {
    text-indent: 2em;
    font-size: 14px;
  }
}
</style>